package comgame.scenes;

import comgame.entities.Player;
import comgame.scenes.ItemManager;
import comgame.scenes.LevelData;
import comgame.entities.Farmland;
import comgame.scenes.PlantScene;
import comgame.scenes.FishpoolScene;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import org.json.JSONObject;
import org.json.JSONArray;

public class DataSaveManager {
    private static final String SAVE_PATH = "src/main/Data_save/save.json";
    private static org.json.JSONObject lastPlayerSaveObj = null;
    private static int lastPlayerMaxHealth = 100;
    public static org.json.JSONObject getLastPlayerSaveObj() { 
        // 每次都从文件重新读取最新数据
        File file = new File(SAVE_PATH);
        if (!file.exists()) {
            return null;
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            JSONObject root = new JSONObject(sb.toString());
            if (root.has("player")) {
                lastPlayerSaveObj = root.getJSONObject("player");
                lastPlayerMaxHealth = lastPlayerSaveObj.getInt("maxHealth");
                return lastPlayerSaveObj;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lastPlayerSaveObj; 
    }
    public static int getLastPlayerMaxHealth() { return lastPlayerMaxHealth; }

    /**
     * 检查新手教程是否已完成
     */
    public static boolean isTutorialCompleted() {
        return com.almasb.fxgl.dsl.FXGL.getWorldProperties().exists("tutorial_completed") ? 
               com.almasb.fxgl.dsl.FXGL.getb("tutorial_completed") : false;
    }

    /**
     * 设置新手教程为已完成
     */
    public static void setTutorialCompleted() {
        com.almasb.fxgl.dsl.FXGL.set("tutorial_completed", true);
    }

    /**
     * 重置新手教程状态（用于测试）
     */
    public static void resetTutorialStatus() {
        com.almasb.fxgl.dsl.FXGL.set("tutorial_completed", false);
    }

    // 存档
    public static void saveAll() {
        // 存档前自动创建目录
        java.io.File dir = new java.io.File("src/main/Data_save");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        JSONObject root = new JSONObject();
        // 玩家数据
        Player player = GameScene.player;
        if (player != null) {
            JSONObject playerObj = new JSONObject();
            playerObj.put("money", player.getMoney());
            playerObj.put("combatLevel", player.getCombatLevel());
            playerObj.put("combatExp", player.getCombatExp());
            playerObj.put("farmingLevel", player.getFarmingLevel());
            playerObj.put("maxHealth", player.getMaxHealth());
            // 装备
            playerObj.put("sword", player.getEquippedItemName("sword"));
            playerObj.put("helmet", player.getEquippedItemName("helmet"));
            playerObj.put("chestplate", player.getEquippedItemName("chestplate"));
            playerObj.put("legging", player.getEquippedItemName("legging"));
            playerObj.put("boot", player.getEquippedItemName("boot"));
            root.put("player", playerObj);
        }
        // 背包数据
        root.put("items", new JSONObject(ItemManager.getInstance().getAllItems()));
        // 关卡数据
        JSONObject levelObj = new JSONObject();
        LevelData levelData = LevelData.getInstance();
        for (int i = 1; i <= 7; i++) {
            levelObj.put(String.valueOf(i), levelData.isLevelUnlocked(i));
        }
        root.put("levels", levelObj);
        // 农田数据
        JSONArray farmlandArr = new JSONArray();
        Farmland[][] farmlands = PlantScene.getFarmlands();
        if (farmlands != null) {
            for (int i = 0; i < farmlands.length; i++) {
                for (int j = 0; j < farmlands[i].length; j++) {
                    Farmland f = farmlands[i][j];
                    if (f != null) {
                        JSONObject fObj = new JSONObject();
                        fObj.put("row", f.getRow());
                        fObj.put("col", f.getCol());
                        fObj.put("cropType", f.getCropType());
                        fObj.put("watered", f.isWatered());
                        fObj.put("fertilized", f.isFertilized());
                        fObj.put("grown", f.isGrown());
                        fObj.put("tilled", f.isTilled());
                        fObj.put("matureTimestamp", f.getMatureTimestamp());
                        farmlandArr.put(fObj);
                    }
                }
            }
        }
        root.put("farmlands", farmlandArr);
        // 鱼塘数据
        JSONObject fishObj = new JSONObject();
        fishObj.put("fishCount", FishpoolScene.fishCount);
        fishObj.put("greenFishCount", FishpoolScene.greenFishCount);
        fishObj.put("grayFishCount", FishpoolScene.grayFishCount);
        fishObj.put("brownFishCount", FishpoolScene.brownFishCount);
        fishObj.put("orangeFishCount", FishpoolScene.orangeFishCount);
        fishObj.put("pinkFishCount", FishpoolScene.pinkFishCount);
        fishObj.put("redKingFishCount", FishpoolScene.redKingFishCount);
        fishObj.put("liangziFishCount", FishpoolScene.liangziFishCount);
        fishObj.put("caveSharkCount", FishpoolScene.caveSharkCount);
        fishObj.put("arcticShrimpCount", FishpoolScene.arcticShrimpCount);
        root.put("fishpool", fishObj);
        // 献祭（祭坛）进度
        try {
            Class<?> altarClass = Class.forName("comgame.scenes.AltarScene");
            java.lang.reflect.Field fCrop = altarClass.getDeclaredField("cropSacrificed");
            fCrop.setAccessible(true);
            boolean[] cropSacrificed = (boolean[]) fCrop.get(null);
            java.lang.reflect.Field fTotal = altarClass.getDeclaredField("totalSacrificedCount");
            fTotal.setAccessible(true);
            int totalSacrificedCount = fTotal.getInt(null);
            java.lang.reflect.Field fRound = altarClass.getDeclaredField("currentRound");
            fRound.setAccessible(true);
            int currentRound = fRound.getInt(null);
            org.json.JSONObject altarObj = new org.json.JSONObject();
            org.json.JSONArray arr = new org.json.JSONArray();
            for (boolean b : cropSacrificed) arr.put(b);
            altarObj.put("cropSacrificed", arr);
            altarObj.put("totalSacrificedCount", totalSacrificedCount);
            altarObj.put("currentRound", currentRound);
            root.put("altar", altarObj);
        } catch (Exception e) { e.printStackTrace(); }
        // 新boss解锁/击败状态
        root.put("newBossUnlocked", comgame.scenes.AltarScene.newBossUnlocked);
        root.put("newBossDefeated", comgame.scenes.AltarScene.newBossDefeated);
        // 自动化种田（妙蛙仙子）状态
        org.json.JSONObject autoFarmObj = new org.json.JSONObject();
        autoFarmObj.put("enabled", com.almasb.fxgl.dsl.FXGL.getWorldProperties().exists("auto_farm_enabled") ? com.almasb.fxgl.dsl.FXGL.getb("auto_farm_enabled") : false);
        autoFarmObj.put("level", com.almasb.fxgl.dsl.FXGL.getWorldProperties().exists("auto_farm_level") ? com.almasb.fxgl.dsl.FXGL.gets("auto_farm_level") : "");
        autoFarmObj.put("interval", com.almasb.fxgl.dsl.FXGL.getWorldProperties().exists("auto_farm_interval") ? com.almasb.fxgl.dsl.FXGL.getd("auto_farm_interval") : 2.0);
        autoFarmObj.put("unlocked", com.almasb.fxgl.dsl.FXGL.getWorldProperties().exists("auto_farm_unlocked") ? com.almasb.fxgl.dsl.FXGL.getb("auto_farm_unlocked") : false);
        root.put("auto_farm", autoFarmObj);
        // 钓鱼阶段进度
        try {
            Class<?> fishingClass = Class.forName("comgame.scenes.FishingScene");
            java.lang.reflect.Field fStage = fishingClass.getDeclaredField("fishingStage");
            fStage.setAccessible(true);
            int fishingStage = fStage.getInt(null);
            root.put("fishingStage", fishingStage);
        } catch (Exception e) { e.printStackTrace(); }
        
        // 新手教程状态
        root.put("tutorialCompleted", com.almasb.fxgl.dsl.FXGL.getWorldProperties().exists("tutorial_completed") ? com.almasb.fxgl.dsl.FXGL.getb("tutorial_completed") : false);
        
        // 写入文件
        try (Writer writer = new OutputStreamWriter(new FileOutputStream(SAVE_PATH), StandardCharsets.UTF_8)) {
            writer.write(root.toString(2));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读档
    public static void loadAll() {
        File file = new File(SAVE_PATH);
        if (!file.exists()) {
            lastPlayerSaveObj = null;
            lastPlayerMaxHealth = 100;
            if (GameScene.player != null) {
                GameScene.player.resetAll();
            }
            return;
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            JSONObject root = new JSONObject(sb.toString());
            // 玩家数据
            if (root.has("player")) {
                JSONObject playerObj = root.getJSONObject("player");
                lastPlayerSaveObj = playerObj;
                lastPlayerMaxHealth = playerObj.getInt("maxHealth");
                // 不要在这里操作GameScene.player实例
            }
            // 背包数据
            if (root.has("items")) {
                JSONObject itemsObj = root.getJSONObject("items");
                for (String key : itemsObj.keySet()) {
                    ItemManager.getInstance().addItem(key, itemsObj.getInt(key) - ItemManager.getInstance().getItemCount(key));
                }
            }
            // 关卡数据
            if (root.has("levels")) {
                JSONObject levelObj = root.getJSONObject("levels");
                LevelData levelData = LevelData.getInstance();
                for (String key : levelObj.keySet()) {
                    if (levelObj.getBoolean(key)) {
                        levelData.unlockLevel(Integer.parseInt(key));
                    }
                }
            }
            // 农田数据
            if (root.has("farmlands")) {
                JSONArray farmlandArr = root.getJSONArray("farmlands");
                Farmland[][] farmlands = PlantScene.getFarmlands();
                for (int i = 0; i < farmlandArr.length(); i++) {
                    JSONObject fObj = farmlandArr.getJSONObject(i);
                    int row = fObj.getInt("row");
                    int col = fObj.getInt("col");
                    if (farmlands != null && row < farmlands.length && col < farmlands[row].length) {
                        Farmland f = farmlands[row][col];
                        if (f != null) {
                            f.setCropType(fObj.optString("cropType", null));
                            f.setWatered(fObj.optBoolean("watered", false));
                            f.setFertilized(fObj.optBoolean("fertilized", false));
                            f.setGrown(fObj.optBoolean("grown", false));
                            f.setTilled(fObj.optBoolean("tilled", false));
                            f.setMatureTimestamp(fObj.optLong("matureTimestamp", 0));
                        }
                    }
                }
            }
            // 鱼塘数据
            if (root.has("fishpool")) {
                JSONObject fishObj = root.getJSONObject("fishpool");
                FishpoolScene.fishCount = fishObj.optInt("fishCount", 0);
                FishpoolScene.greenFishCount = fishObj.optInt("greenFishCount", 0);
                FishpoolScene.grayFishCount = fishObj.optInt("grayFishCount", 0);
                FishpoolScene.brownFishCount = fishObj.optInt("brownFishCount", 0);
                FishpoolScene.orangeFishCount = fishObj.optInt("orangeFishCount", 0);
                FishpoolScene.pinkFishCount = fishObj.optInt("pinkFishCount", 0);
                FishpoolScene.redKingFishCount = fishObj.optInt("redKingFishCount", 0);
                FishpoolScene.liangziFishCount = fishObj.optInt("liangziFishCount", 0);
                FishpoolScene.caveSharkCount = fishObj.optInt("caveSharkCount", 0);
                FishpoolScene.arcticShrimpCount = fishObj.optInt("arcticShrimpCount", 0);
            }
            // 自动化种田（妙蛙仙子）状态
            if (root.has("auto_farm")) {
                JSONObject autoFarmObj = root.getJSONObject("auto_farm");
                com.almasb.fxgl.dsl.FXGL.set("auto_farm_enabled", autoFarmObj.optBoolean("enabled", false));
                com.almasb.fxgl.dsl.FXGL.set("auto_farm_level", autoFarmObj.optString("level", ""));
                com.almasb.fxgl.dsl.FXGL.set("auto_farm_interval", autoFarmObj.optDouble("interval", 2.0));
                com.almasb.fxgl.dsl.FXGL.set("auto_farm_unlocked", autoFarmObj.optBoolean("unlocked", false));
            }
            // 献祭（祭坛）进度
            if (root.has("altar")) {
                try {
                    org.json.JSONObject altarObj = root.getJSONObject("altar");
                    Class<?> altarClass = Class.forName("comgame.scenes.AltarScene");
                    java.lang.reflect.Field fCrop = altarClass.getDeclaredField("cropSacrificed");
                    fCrop.setAccessible(true);
                    org.json.JSONArray arr = altarObj.getJSONArray("cropSacrificed");
                    boolean[] cropSacrificed = new boolean[arr.length()];
                    for (int i = 0; i < arr.length(); i++) cropSacrificed[i] = arr.getBoolean(i);
                    fCrop.set(null, cropSacrificed);
                    java.lang.reflect.Field fTotal = altarClass.getDeclaredField("totalSacrificedCount");
                    fTotal.setAccessible(true);
                    fTotal.setInt(null, altarObj.getInt("totalSacrificedCount"));
                    java.lang.reflect.Field fRound = altarClass.getDeclaredField("currentRound");
                    fRound.setAccessible(true);
                    fRound.setInt(null, altarObj.getInt("currentRound"));
                } catch (Exception e) { e.printStackTrace(); }
            }
            // 新boss解锁/击败状态
            if (root.has("newBossUnlocked")) {
                comgame.scenes.AltarScene.newBossUnlocked = root.getBoolean("newBossUnlocked");
            }
            if (root.has("newBossDefeated")) {
                comgame.scenes.AltarScene.newBossDefeated = root.getBoolean("newBossDefeated");
            }
            // 钓鱼阶段进度
            if (root.has("fishingStage")) {
                try {
                    Class<?> fishingClass = Class.forName("comgame.scenes.FishingScene");
                    java.lang.reflect.Field fStage = fishingClass.getDeclaredField("fishingStage");
                    fStage.setAccessible(true);
                    fStage.setInt(null, root.getInt("fishingStage"));
                } catch (Exception e) { e.printStackTrace(); }
            }
            
            // 新手教程状态
            if (root.has("tutorialCompleted")) {
                com.almasb.fxgl.dsl.FXGL.set("tutorial_completed", root.getBoolean("tutorialCompleted"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

} 